<template>
  <el-drawer v-model="drawer" direction="rtl" :before-close="handleClose">
    <template #header>
      <h4>添加知识库</h4>
    </template>
    <template #default>
      <el-form ref="formRefs" :model="form" label-width="80px" :rules="rules">
        <el-form-item label="标题" prop="title">
          <el-input v-model="form.title" />
        </el-form-item>
        <el-form-item label="描述信息" prop="decs">
          <el-input v-model="form.decs" type="textarea" />
        </el-form-item>
        <el-form-item label="封面">
          <el-upload
            class="avatar-uploader"
            :action="uploadUrl"
            name="files"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
          >
            <img v-if="form.img" :src="base + form.img" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon">
              <Plus />
            </el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item>
          <el-button @click="handleClose">关闭</el-button>
          <el-button type="primary" @click="confirmClick">确定</el-button>
        </el-form-item>
      </el-form>
    </template>
  </el-drawer>
</template>

<script setup lang="ts">
import { ref, reactive, watch } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import type { FormInstance, FormRules } from 'element-plus';
import { addStoreApi, editStoreApi } from '@/service/api';
import { base, uploadUrl } from '@/service/config';
import { sleep } from '@/utils';

const props = defineProps({
  rowData: {
    type: Object,
    default: () => {}
  }
});

const drawer = ref(false);
const isModify = ref(false); //是否修改
const formRefs = ref<FormInstance>();

const form = reactive({
  title: '',
  decs: '',
  img: ''
});
const emit = defineEmits(['addSuccess']);
const rules = reactive<FormRules>({
  title: [{ required: true, message: '标题不能为空', trigger: 'blur' }],
  decs: [{ required: true, message: '描述信息不能为空', trigger: 'blur' }]
});

function confirmClick() {
  formRefs.value?.validate((vali) => {
    if (vali) {
      addStoreFn();
    } else {
      console.log('验证未通过');
    }
  });
}
const addStoreFn = async () => {
  let res: Res;
  if (!isModify.value) {
    res = await addStoreApi({ ...form });
  } else {
    res = await editStoreApi({ id: props.rowData._id, ...form });
  }
  if (res.code !== 201) return ElMessage.error(res.errors.msg);
  ElMessage.success(res.msg);
  emit('addSuccess');
  handleClose();
};
const handleAvatarSuccess = async (res) => {
  if (res.error) return ElMessage.error('封面上传失败');
  ElMessage.success('封面上传成功');
  // function sleep(ms) {
  //   return new Promise((resolve) => setTimeout(resolve, ms));
  // }
  await sleep(1000);
  form.img = res.data.url;
};

const resetForm = () => {
  form.title = '';
  form.decs = '';
  form.img = '';
  isModify.value = false;
};

const addStore = () => {
  drawer.value = true;
};
const handleClose = () => {
  drawer.value = false;
  resetForm();
};

defineExpose({ form, addStore, isModify });
</script>

<style scoped lang="less">
.bar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 20px 20px;
}

.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
